package jfilters.filters.blur;

/*
    Copyright Janne Liljeblad 2008.

    This file is part of JFilters.

    JFilters is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    JFilters is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JFilters.  If not, see <http://www.gnu.org/licenses/>.
*/

import jfilters.filters.JFilter;
import jfilters.libmath.JFMath;
import jfilters.lib.PixelRow;
import java.awt.image.*;
import java.awt.*;

public class JFBlur extends JFilter
{
	public JFBlur(){}

	public BufferedImage filter( BufferedImage sourceImg, BufferedImage destinationImg )
	{
		WritableRaster destination = destinationImg.getRaster();
		WritableRaster source = sourceImg.getRaster();
		int width = source.getWidth();
		int height = source.getHeight();
		
		int bytes = source.getNumBands();

		int startRow = 0;
		int endRow = height - 1;

		int startCol = 0;
		int endCol = width - 1;

		PixelRow pr = prepareRow( source, startRow -1 );// wont be clamped
		PixelRow cr = prepareRow( source, startRow );
		PixelRow nr;
		PixelRow dr;
		PixelRow tmp;

		for ( int row = startRow; row <= endRow; row++)
		{
			/*  prepare the next row  */
			nr = prepareRow( source, row + 1 );
			dr = prepareRow( destination, row );
		
			for ( int col = startCol; col < width * bytes; col++)
			{
					      dr.setSample( col,(pr.getSample( col - bytes ) + 
								pr.getSample( col) +
								pr.getSample( col + bytes) +
								cr.getSample( col - bytes) +
								cr.getSample( col ) +
								cr.getSample( col + bytes) +
								nr.getSample( col - bytes) +
								nr.getSample( col) +
								nr.getSample( col + bytes))
								/ 9 );

			}
			/* Write data into raster */
			dr.commitData();

			tmp = pr;
			pr = cr;
			cr = nr;
			nr = tmp;
		}

		return destinationImg;
	}

	private PixelRow prepareRow( WritableRaster raster, int y )
	{
		y = JFMath.CLAMP( y, 0, raster.getHeight() - 1 );
		return new PixelRow( raster, y, PixelRow.CLAMP_EDGES );
	}

}//end class